package com.bondmatch.demo.service;

import com.bondmatch.demo.mapper.MatchResultMapper;
import com.bondmatch.demo.mapper.TransRequestMapper;
import com.bondmatch.demo.model.MatchResult;
import com.bondmatch.demo.model.Result;
import com.bondmatch.demo.model.TransRequest;
import com.bondmatch.demo.utils.Pager;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class MatchResultService {
    @Resource
    private MatchResultMapper matchResultMapper;
    @Resource
    private TransRequestMapper transRequestMapper;

    /**
     * 分页查询
     * @param pageNum
     * @param pageSize
     * @return
     */
    public Pager<TransRequest> findByPager(int pageNum, int pageSize){
        Pager<TransRequest> pager = new Pager<TransRequest>();
        Page<TransRequest> res = PageHelper.startPage(pageNum, pageSize);
        matchResultMapper.selectAll();
        pager.setRows(res.getResult());
        pager.setTotal(res.getTotal());
        return pager;
    }

    /**
     * 将两条交易请求的信息结合，插入匹配结果表中，并改变交易请求状态码
     * @param matchArray
     */
    public void combineTrans(ArrayList<Result> matchArray) {
        for (int i = 0; i < matchArray.size(); i++) {
            MatchResult matchResult = new MatchResult();
            //匹配对应的两条数据
            TransRequest transRequest= transRequestMapper.selectByPrimaryKey(matchArray.get(i).getBuerId());//买方ID
            TransRequest transRequest1= transRequestMapper.selectByPrimaryKey(matchArray.get(i).getSellId());//卖方ID
            matchResult.setBondCode(transRequest.getBondCode());
            //买方编号
            matchResult.setBuyerNo(transRequest.getCustomerNo());
            //卖方编号
            matchResult.setSellerNo(transRequest1.getCustomerNo());
            matchResult.setTransactionDate(new Date());
            matchResult.setTransactionPrice(transRequest.getPrice());
            matchResultMapper.insert(matchResult);
            //改变交易请求状态码 state = 1
            transRequestMapper.updateState(matchArray.get(i).getBuerId());
            transRequestMapper.updateState(matchArray.get(i).getSellId());
        }
    }
}
